var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

var onlen=0;//在线人数
var onli=[];//在线人员id名称


io.on('connection', function(socket,msg){
     
	var uid=socket.id;
    var name;

    // 对message事件的监听,请收页面发过来的信息
    socket.on('message', function(msg){
     name=msg;
     console.log(name+'登录');
     socket.broadcast.emit('onli',name);

     var list={name:name,uid:uid};
     //发送人数
     onli.push(list);
     socket.broadcast.emit('open',onli);
     socket.emit('open',onli);

    });

    //监听出退事件
    socket.on('disconnect', function () {
      var uid=socket.id;
      var len=onli.length;
      console.log(name+'退出')
      socket.broadcast.emit('outli',name);//谁退出了
      for(var i=0;i<len;i++){
          var onliID=onli[i].uid;
          if(onliID==uid){
            onli.splice(i,1);
            socket.broadcast.emit('open',onli);//广播在线人数
            break;
          };
      };
    });



    socket.on('chat', function (msg) {
    	socket.emit('mtall',msg.txt);//自己接收
      	socket.broadcast.emit('tall',{name:name,txt:msg.txt});//发给其他用户
    });





});

http.listen(18080, function(){
  console.log('listening on *:18080');
});